package jnpf.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.util.DynDicUtil;
import jnpf.entity.*;
import jnpf.model.zxgl_aIAssistant.ZXGL_AI_UploadKnowledge;
import jnpf.model.zxgl_aIAssistant.ZXGL_AiTopicinsert;
import jnpf.model.zxgl_aIAssistant.ZXGL_SeeChat;
import jnpf.model.zxgl_lixiangguanli.*;
import jnpf.model.zxgl_renwufankui.ZXGL_AI_Task;
import jnpf.model.zxgl_xiangmufankui.ZXGL_AI_ProjectEvaluation;
import jnpf.model.zxgl_xmcfzgbmjs.ZXGL_AI_responsibility;
import jnpf.service.*;
import jnpf.util.FileUploadUtil;
import jnpf.util.StringUtil;
import jnpf.utils.AIUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ZXGL_AI_InterfaceController
 * @Description AI接口
 * @Author ZCX
 * @Date 2025-03-19
 * @Version 1.0
 **/
@Slf4j
@RestController
@Api(tags = "AI接口", value = "zxgl")
@RequestMapping("/ZXGL_AI")
public class ZXGL_AI_InterfaceController {
    private static final Logger logger = LoggerFactory.getLogger(ZXGL_LiXiangGuanLiController.class);

    @Autowired
    private DynDicUtil dynDicUtil;

    @Autowired
    private AIUtil AIUtil;

    @Autowired
    private ZXGL_XMCFZGBMJS_MingXiService zxglXmcfzgbmjsMingXiService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    // region 立项管理、部门确认、项目反馈、任务反馈、项目结项、项目分解任务 查询结果 AI调用
    /**
     * @param zxgl_ai_param:
     * @Description:AI 根据部门分工预分配重点项目-智能立项接口 (立项管理)
     * @Author: ZhaoChenXu
     * @Date: 2025-03-20
     * @return: jnpf.base.ActionResult
     **/
    @ApiOperation("立项管理AI")
    @PostMapping("/allocateProjectByDep")
    public ActionResult allocateProjectByDep(@RequestBody ZXGL_AI_Param zxgl_ai_param) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            // 调用AI 根据部门分工预分配重点项目-智能立项接口
            // byte[] bytes = fileUploadProvider.getInputStream(zxgl_ai_param.getZxgl_fileInfoList().get(0).getName(), zxgl_ai_param.getZxgl_fileInfoList().get(0).getUrl());
            // String url = "http://192.168.40.158:30000/api/file/Download?encryption=" + zxgl_ai_param.getZxglFileInfo().getKey();
//            String url = aiConfig.getDownloadUrl() + "/api/file/Download?encryption=" + zxgl_ai_param.getZxglFileInfo().getKey();
//            byte[] bytes = new byte[0];
//            try {
//                bytes = zxgl_ai_service.downloadFile(url);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            byte[] bytes = fileUploadUtil.getInputStream(zxgl_ai_param.getZxglFileInfo().getKey());
            logger.info("bytes:{}----------->" + bytes);
            String aiResult = AIUtil.allocationProjectByDep(token, zxgl_ai_param, bytes);
            if (aiResult != null) {
                return ActionResult.success("调用AI接口成功");
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    // region 注释

    /**
     * @Description:AI分配项目给牵头人员、项目经理、协作人员
     * @Author: ZhaoChenXu
     * @Date: 2025-03-20 1:45
     * @return: jnpf.base.ActionResult
     **/
    /*@PostMapping("/allocationResponsibility")
    public ActionResult allocateResponsibility(@RequestBody ZXGL_AI_responsibility zxgl_ai_responsibility) {
        //先获取token
        String token = zxgl_ai_service.getAiToken();
        if (token != null) {
            //调用AI 根据部门分工预分配重点项目-智能立项接口
//            byte[] bytes = fileUploadProvider.getInputStream(zxgl_ai_responsibility.getZxgl_fileInfo().getName(), zxgl_ai_responsibility.getZxgl_fileInfo().getUrl());
            String url = "http://192.168.40.158:30000/api/file/Download?encryption=" + zxgl_ai_responsibility.getZxgl_fileInfo().getKey();
            byte[] bytes = new byte[0];
            try {
                bytes = zxgl_ai_service.downloadFile(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            logger.info("bytes:{}----------->" + bytes);

            String aiResult = zxgl_ai_service.allocationProjectByPerson(token, zxgl_ai_responsibility, bytes);
            if (aiResult != null) {
                return ActionResult.success("调用AI接口成功");
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }*/

    // endregion

    /**
     * 部门确认
     *
     * @param id
     * @param zXGL_FileInfo
     * @return
     */
    @ApiOperation("部门确认AI")
    @PutMapping("/allocateResponsibilityById/{id}")
    public ActionResult allocateResponsibilityById(@PathVariable String id, @RequestBody jnpf.model.zxgl_xmcfzgbmjs.ZXGL_FileInfo zXGL_FileInfo) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            QueryWrapper<ZXGL_XMCFZGBMJS_MingXiEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ZXGL_XMCFZGBMJS_MingXiEntity::getMainid, id);
            List<ZXGL_XMCFZGBMJS_MingXiEntity> list = zxglXmcfzgbmjsMingXiService.list(queryWrapper);
            log.info("list===================>" + list);
            if (list != null && list.size() > 0) {
                ZXGL_AI_responsibility zxgl_ai_responsibility = new ZXGL_AI_responsibility();
                for (ZXGL_XMCFZGBMJS_MingXiEntity entity : list) {
                    zxgl_ai_responsibility.setFlowId(entity.getId());
                    zxgl_ai_responsibility.setCallbackUrl(zXGL_FileInfo.getCallbackUrl());
                    ZXGL_AI_ProjectInfo info = new ZXGL_AI_ProjectInfo();
                    info.setProjectName(entity.getXmmc());
                    info.setProjectFrom(dynDicUtil.getDicName(entity.getXmly(), "667353988936504645"));
                    info.setProjectType(dynDicUtil.getDicName(entity.getXmlx(), "670160918163781253"));
                    info.setMainDepartment(entity.getZrbm());
                    info.setWorkObjective(entity.getGzmb());
                    zxgl_ai_responsibility.setZxgl_ai_projectInfo(info);
                    zxgl_ai_responsibility.setZxgl_fileInfo(zXGL_FileInfo);
                    // String url = "http://192.168.40.158:30000/api/file/Download?encryption=" + zXGL_FileInfo.getKey();
//                    String url = aiConfig.getDownloadUrl() + "/api/file/Download?encryption=" + zXGL_FileInfo.getKey();
//                    byte[] bytes = new byte[0];
//                    try {
//                        bytes = AIUtil.downloadFile(url);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
                    byte[] bytes = fileUploadUtil.getInputStream(zXGL_FileInfo.getKey());
                    logger.info("bytes:{}----------->" + bytes);

                    String aiResult = AIUtil.allocationProjectByPerson(token, zxgl_ai_responsibility, bytes);
                }
            } else {
                return ActionResult.fail("明细表无数据");
            }
            return ActionResult.success("调用接口成功！");
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /**
     * 项目分解至部门查询结果
     *
     * @param id
     * @return
     */
    @ApiOperation("项目分解至部门查询结果")
    @GetMapping("/buesponsibilityQuery/{id}")
    public ActionResult queryAiProcessing(@PathVariable String id) {
        String token = AIUtil.getAiToken();
        if (token != null) {
            QueryWrapper<ZXGL_XMCFZGBMJS_MingXiEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ZXGL_XMCFZGBMJS_MingXiEntity::getMainid, id);
            List<ZXGL_XMCFZGBMJS_MingXiEntity> list = zxglXmcfzgbmjsMingXiService.list(queryWrapper);
            // List<ZXGL_XMCFZGBMJS_MingXiEntity> updateList = new ArrayList<>();
            String failMsg = "";
            if (list != null && list.size() > 0) {
                for (ZXGL_XMCFZGBMJS_MingXiEntity entity : list) {
                    ZXGL_AI_QueryAIProcessing queryAIProcessing = new ZXGL_AI_QueryAIProcessing();
                    queryAIProcessing.setFlowId(entity.getId());
                    queryAIProcessing.setBusinessType("responsibility_allocation");
                    JSONObject json = AIUtil.queryAiProcessing(token, queryAIProcessing);

                    if (json != null && json.getInteger("code").equals(200) && json.getJSONObject("data") != null) {
                        switch (json.getJSONObject("data").getInteger("processingProgress")) {
                            case 0:
                                return ActionResult.success("接收任务");
                            case 1:
                                return ActionResult.success("文档读取");
                            case 2:
                                return ActionResult.success("模型读取");
                            case 3:
                                // entity.setZrr(json.getJSONObject("data").getJSONObject("returnJson").getJSONObject("projectManager").getString("id"));
                                // entity.setQtry(json.getJSONObject("data").getJSONObject("returnJson").getJSONObject("leadPerson").getString("id"));
                                // entity.setXzr(json.getJSONObject("data").getJSONObject("returnJson").getJSONObject("collaborator").getString("id"));
                                String gw = json.getJSONObject("data").getJSONObject("returnJson").getString("positionName");
                                log.info("positionName:=============================>" + gw);
                                zxglXmcfzgbmjsMingXiService.updateGwById(gw, entity.getId());
                                // updateList.add(entity);
                                break;
                            case 4:
                                failMsg += entity.getXmmc() + "AI解析失败<br>";
                                break;
                        }
                    }
                }
//                if (updateList.size() > 0) {
//                    log.info("updateList:========================>" + updateList);
//                    boolean update = zxglXmcfzgbmjsMingXiService.updateBatchById(updateList);
//                    log.info("update:{}==============================>", update);
//                }
                if (StringUtil.isEmpty(failMsg)) {
                    return ActionResult.success("读取成功");
                }
                return ActionResult.success("读取成功", failMsg);
            }
            return ActionResult.fail("查询失败，数据不存在！");
        }
        return ActionResult.fail("AI登录失败！");
    }

    /**
     * 根据岗位职责预分解任务预分配任务列表
     * 项目分解任务
     *
     * @param zXGL_AI_Task
     * @return
     */
    @ApiOperation("项目分解任务AI")
    @PostMapping("/allocateProjectTask")
    public ActionResult allocateProjectTask(@RequestBody jnpf.model.zxgl_xiangmufenjie.ZXGL_AI_Task zXGL_AI_Task) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {

            log.info("zXGL_AI_Task.getZXGL_FileInfo().getKey():" + zXGL_AI_Task.getZXGL_FileInfo().getKey());
            // String url = "http://192.168.40.158:30000/api/file/Download?encryption=" + zXGL_AI_Task.getZXGL_FileInfo().getKey();
//            String url = aiConfig.getDownloadUrl() + "/api/file/Download?encryption=" + zXGL_AI_Task.getZXGL_FileInfo().getKey();
//            byte[] bytes = new byte[0];
//            try {
//                bytes = AIUtil.downloadFile(url);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            byte[] bytes = fileUploadUtil.getInputStream(zXGL_AI_Task.getZXGL_FileInfo().getKey());
            logger.info("bytes:{}----------->" + bytes);
            //调用AI 根据部门分工预分配重点项目-智能立项接口
            //byte[] bytes = fileUploadProvider.getInputStream(zxgl_ai_responsibility.getZxgl_fileInfoList().get(0).getName(),zxgl_ai_responsibility.getZxgl_fileInfoList().get(0).getUrl());
            String aiResult = AIUtil.allocationProjectTask(token, zXGL_AI_Task, bytes);
            if (aiResult != null) {
                return ActionResult.success(aiResult);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /***
     * 任务反馈AI
     * @param zxgl_ai_task
     * @return
     */
    @ApiOperation("任务反馈AI")
    @PostMapping("/allocationTask")
    public ActionResult allocationTask(@RequestBody ZXGL_AI_Task zxgl_ai_task) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            //调用AI 根据部门分工预分配重点项目-智能立项接口
//            byte[] bytes = fileUploadProvider.getInputStream(zxgl_ai_param.getZxgl_fileInfoList().get(0).getName(), zxgl_ai_param.getZxgl_fileInfoList().get(0).getUrl());
            // String url = "http://192.168.40.158:30000/api/file/Download?encryption=" + zxgl_ai_rwfk_task.getAttachments().getKey();
//            String url = aiConfig.getDownloadUrl() + "/api/file/Download?encryption=" + zxgl_ai_rwfk_task.getAttachments().getKey();
//            byte[] bytes = new byte[0];
//            try {
//                if (StringUtil.isNotEmpty(zxgl_ai_rwfk_task.getAttachments().getKey())) {
//                    bytes = AIUtil.downloadFile(url);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            List<ZXGL_AI_UploadKnowledge> knowledges = new ArrayList<>();
            if(zxgl_ai_task.getAttachments() != null && zxgl_ai_task.getAttachments().size() > 0){
                for (ZXGL_FileInfo fileInfo : zxgl_ai_task.getAttachments()) {
                    if (StringUtil.isNotEmpty(fileInfo.getKey())) {
                        byte[] bytes = fileUploadUtil.getInputStream(fileInfo.getKey());
                        ZXGL_AI_UploadKnowledge knowledge = new ZXGL_AI_UploadKnowledge();
                        knowledge.setName(fileInfo.getName());
                        knowledge.setBytes(bytes);
                    }
                }
            }

            logger.info("bytes:{}----------->" + knowledges);
            String aiResult = AIUtil.allocationTask(token, zxgl_ai_task, knowledges);
            if (aiResult != null) {
                return ActionResult.success(aiResult);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /***
     * 项目反馈AI
     * @param zxglAiProjectEvaluation
     * @return
     */
    @ApiOperation("项目反馈AI")
    @PostMapping("/allocationProjectFk")
    public ActionResult allocationProjectFk(@RequestBody ZXGL_AI_ProjectEvaluation zxglAiProjectEvaluation) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            // String url = "http://192.168.40.158:30000/api/file/Download?encryption=" + zxglAiProjectEvaluation.getAttachments().getKey();
//            String url = aiConfig.getDownloadUrl() + "/api/file/Download?encryption=" +  zxglAiProjectEvaluation.getAttachments().getKey();
//            byte[] bytes = new byte[0];
//            try {
//                if (StringUtil.isNotEmpty(zxglAiProjectEvaluation.getAttachments().getKey())) {
//                    bytes = AIUtil.downloadFile(url);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            List<ZXGL_AI_UploadKnowledge> knowledges = new ArrayList<>();
            if(zxglAiProjectEvaluation.getAttachments() != null && zxglAiProjectEvaluation.getAttachments().size() > 0){
                for (jnpf.model.zxgl_xiangmufenjie.ZXGL_FileInfo fileInfo : zxglAiProjectEvaluation.getAttachments()) {
                    if (StringUtil.isNotEmpty(fileInfo.getKey())) {
                        byte[] bytes = fileUploadUtil.getInputStream(fileInfo.getKey());
                        ZXGL_AI_UploadKnowledge knowledge = new ZXGL_AI_UploadKnowledge();
                        knowledge.setName(fileInfo.getName());
                        knowledge.setBytes(bytes);
                    }
                }
            }

//            byte[] bytes = new byte[0];
//            if (StringUtil.isNotEmpty(zxglAiProjectEvaluation.getAttachments().getKey())) {
//                bytes = fileUploadUtil.getInputStream(zxglAiProjectEvaluation.getAttachments().getKey());
//            }
            logger.info("bytes:{}----------->" + knowledges);
            //调用AI 根据部门分工预分配重点项目-智能立项接口
            String aiResult = AIUtil.allocationProjectFk(token, zxglAiProjectEvaluation, knowledges);
            if (aiResult != null) {
                return ActionResult.success(aiResult);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /**
     * 查询结果
     *
     * @param zxgl_ai_queryAIProcessing
     * @return
     */
    @ApiOperation("查询结果")
    @PostMapping("/queryAiProcessing")
    public ActionResult queryAiProcessing(@RequestBody ZXGL_AI_QueryAIProcessing zxgl_ai_queryAIProcessing) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            JSONObject aiResult = AIUtil.queryAiProcessing(token, zxgl_ai_queryAIProcessing);
            if (aiResult.getBoolean("success")) {
                return ActionResult.success("查询成功", aiResult.getJSONObject("data"));
            } else {
                return ActionResult.fail("查询失败");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    // endregion

    // region ai助手

    /**
     * AI 助手-创建主题接口（只有新开主题并且当问题发送出去的时候才会调用）
     *
     * @param zXGL_AiTopicinsert
     * @return
     */
    @ApiOperation("AI助手-创建主题接口")
    @PostMapping("/aiTopicinsert")
    public ActionResult aiTopicinsert(@RequestBody ZXGL_AiTopicinsert zXGL_AiTopicinsert) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            String topicName = "";
            if (zXGL_AiTopicinsert.getTopicName().length() > 20) {
                topicName = zXGL_AiTopicinsert.getTopicName().substring(0, 20);
            } else {
                topicName = zXGL_AiTopicinsert.getTopicName();
            }
            zXGL_AiTopicinsert.setTopicName(topicName);
            String result = AIUtil.aiTopicinsert(token, zXGL_AiTopicinsert);
            if (!StringUtil.isEmpty(result)) {
                return ActionResult.success("创建成功", result);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /**
     * AI 助手-智能问答接口（问答范围：所属项目的知识库相关项目文档）
     *
     * @param zXGL_SeeChat
     * @return
     */
    @ApiOperation("AI助手-智能问答接口")
    @PostMapping("/sseChat")
    public ActionResult sseChat(@RequestBody ZXGL_SeeChat zXGL_SeeChat) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            String result = AIUtil.sseChat(token, zXGL_SeeChat);
            if (!StringUtil.isEmpty(result)) {
                return ActionResult.success("问答成功", result);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /**
     * AI 助手-主题列表接口（分页查询，默认当前第1页 每页10条，创建时间倒序返回）
     *
     * @return
     */
    @ApiOperation("AI助手-主题列表接口")
    @GetMapping("/aiTopicQueryPage/{projectId}")
    public ActionResult aiTopicQueryPage(@PathVariable String projectId) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            String result = AIUtil.aiTopicQueryPage(token,projectId);
            if (!StringUtil.isEmpty(result)) {
                return ActionResult.success("查询成功", result);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /**
     * AI 助手-会话列表接口（分页查询，默认当前第1页 每页10条，创建时间倒序返回）
     *
     * @param topicId
     * @return
     */
    @ApiOperation("AI助手-会话列表接口")
    @GetMapping("/aiSessionQueryPage/{topicId}")
    public ActionResult aiSessionQueryPage(@PathVariable String topicId) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            String result = AIUtil.aiSessionQueryPage(token, topicId);
            if (!StringUtil.isEmpty(result)) {
                return ActionResult.success("问答成功", result);
            } else {
                return ActionResult.fail("调用AI接口失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }

    /**
     * AI登录获取Token
     *
     * @return
     */
    @ApiOperation("AI登录获取Token")
    @GetMapping("/aiLogin")
    public ActionResult aiLogin() {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            String result = AIUtil.getAiToken();
            if (!StringUtil.isEmpty(result)) {
                return ActionResult.success("登录成功", result);
            } else {
                return ActionResult.fail("登录失败！");
            }
        } else {
            return ActionResult.fail("登录失败！");
        }
    }

    @ApiOperation("AI助手-删除主题")
    @DeleteMapping("/aiTopicDelete")
    public ActionResult aiTopicDelete(@RequestParam("idList") List<Integer> idList) {
        //先获取token
        String token = AIUtil.getAiToken();
        if (token != null) {
            Boolean isTrue = AIUtil.aiTopicDelete(token, idList);
            log.info("isTrue:" + isTrue);
            if (isTrue) {
                return ActionResult.success("删除成功");
            } else {
                return ActionResult.fail("删除失败！");
            }
        } else {
            return ActionResult.fail("获取token失败！");
        }
    }
    // endregion


}
